// src/services/ai.ts
import { AI_CONFIG, type ChatMessage } from '../config/ai'
class AIService {
  private apiKey: string
  private apiUrl: string
  private controller: AbortController | null = null
  private reader: ReadableStreamDefaultReader | null = null
  private isStopped: boolean = false
  private lastMessages: ChatMessage[] | null = null // 保存上次的消息记录

  constructor() {
    this.apiKey = AI_CONFIG.DEEPSEEK_API_KEY
    this.apiUrl = AI_CONFIG.DEEPSEEK_API_URL
  }

  stopGeneration() {
    this.isStopped = true
    if (this.controller) {
      this.controller.abort()
    }
    if (this.reader) {
      this.reader.cancel()
    }
  }

  // 保存上下文用于继续生成
  private saveContext(messages: ChatMessage[]) {
    this.lastMessages = [...messages]
  }

  async chatStream(messages: ChatMessage[], onProgress: (content: string) => void, continueGeneration: boolean = false): Promise<string> {
    try {
      this.isStopped = false
      this.controller = new AbortController()

      // 如果是继续生成，使用保存的上下文
      if (continueGeneration && this.lastMessages) {
        messages = this.lastMessages
      } else {
        this.saveContext(messages)
      }

      const response = await fetch(this.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`,
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: messages,
          stream: true
        }),
        signal: this.controller.signal
      })

      if (!response.ok) {
        const error = await response.json()
        throw new Error(error.error?.message || '请求失败')
      }

      if (!response.body) {
        throw new Error('Response body is null')
      }

      this.reader = response.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''
      let fullResponse = ''

      try {
        while (true) {
          if (this.isStopped) {
            return fullResponse // 如果停止了，返回当前累积的响应
          }

          const { done, value } = await this.reader.read()
          if (done) break

          // 检查是否已被中断
          if (!this.controller || this.controller.signal.aborted) {
            throw new Error('生成已停止')
          }

          buffer += decoder.decode(value, { stream: true })
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''

          for (const line of lines) {
            if (line.trim() === '') continue
            if (line.trim() === 'data: [DONE]') return fullResponse

            try {
              const data = JSON.parse(line.replace(/^data: /, ''))
              if (data.choices[0]?.delta?.content) {
                fullResponse += data.choices[0].delta.content
                onProgress(fullResponse)
              }
            } catch (e) {
              console.warn('Failed to parse line:', line)
            }
          }
        }
      } catch (error) {
       if (this.isStopped) {
          return fullResponse // 如果是因为停止而抛出的错误，返回当前响应
        }
        throw error
      }

      return fullResponse
    } catch (error: any) {
      if (this.isStopped) {
        return error.partialResponse || '' // 如果是停止导致的错误，返回部分响应
      }
      console.error('AI Chat Error:', error)
      throw new Error(error.message || '与 AI 对话时发生错误')
    } finally {
      if (!this.isStopped) {
        // 只有在正常完成时才清除上下文
        this.lastMessages = null
      }
      this.reader = null
      this.controller = null
    }
  }
  canContinueGeneration(): boolean {
    return this.lastMessages !== null
  }
}

export const aiService = new AIService()